package dev.werillib.utils

import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.text.TextUtils
import java.io.File

object FileUtil {

    /**
     * 获取apk下载地址
     *
     * @param packageName
     * @return
     */
    fun getDownloadApkCachePath(packageName: String): String {

        val appCachePath: String = if (checkSDCard()) {
            Environment.getExternalStorageDirectory().toString() + "/" + packageName + "/"
        } else {
            Environment.getDataDirectory().path + "/" + packageName + "/"
        }

        val file = File(appCachePath)
        if (!file.exists()) {
            file.mkdirs()
        }
        return appCachePath
    }

    /**
     *
     */
    private fun checkSDCard(): Boolean {
        return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
    }

    @SuppressLint("SdCardPath")
    fun getLocalPath(): String {
        val fileDir = "werilTakePhoto"
        return if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            Environment.getExternalStorageDirectory().toString() + "/" + "weril"
        } else {
            "/data/data/$fileDir/weril"
        }
    }

    fun create(absPath: String): Boolean {
        return create(absPath, false)
    }

    fun create(absPath: String, force: Boolean): Boolean {
        when {
            TextUtils.isEmpty(absPath) -> return false
            exists(absPath) -> return true
            else -> {
                val parentPath = getParent(absPath)
                mkdirs(parentPath, force)

                return try {
                    val file = File(absPath)
                    file.createNewFile()
                } catch (var4: Exception) {
                    var4.printStackTrace()
                    false
                }
            }
        }
    }

    fun mkdirs(absPath: String): Boolean {
        return mkdirs(absPath, false)
    }

    fun mkdirs(absPath: String?, force: Boolean): Boolean {
        val file = File(absPath!!)
        if (exists(absPath) && !isFolder(absPath)) {
            if (!force) {
                return false
            }

            delete(file)
        }

        try {
            file.mkdirs()
        } catch (var4: Exception) {
            var4.printStackTrace()
        }

        return exists(file)
    }

    fun isFolder(absPath: String): Boolean {
        val exists = exists(absPath)
        return if (!exists) {
            false
        } else {
            val file = File(absPath)
            file.isDirectory
        }
    }

    fun move(srcPath: String, dstPath: String): Boolean {
        return move(srcPath, dstPath)
    }

    fun move(srcPath: String, dstPath: String, force: Boolean): Boolean {
        if (!TextUtils.isEmpty(srcPath) && !TextUtils.isEmpty(dstPath)) {
            if (!exists(srcPath)) {
                return false
            } else {
                if (exists(dstPath)) {
                    if (!force) {
                        return false
                    }

                    delete(dstPath)
                }

                return try {
                    val srcFile = File(srcPath)
                    val dstFile = File(dstPath)
                    srcFile.renameTo(dstFile)
                } catch (var5: Exception) {
                    var5.printStackTrace()
                    false
                }

            }
        } else {
            return false
        }
    }

    fun delete(absPath: String): Boolean {
        return if (TextUtils.isEmpty(absPath)) {
            false
        } else {
            val file = File(absPath)
            delete(file)
        }
    }

    fun delete(file: File): Boolean {
        return if (!exists(file)) {
            true
        } else if (file.isFile) {
            file.delete()
        } else {
            var result = true
            val files = file.listFiles()

            for (index in files!!.indices) {
                result = result or delete(files[index])
            }

            result = result or file.delete()
            result
        }
    }

    fun getParent(absPath: String): String? {
        var mAbsPath = absPath
        return if (TextUtils.isEmpty(mAbsPath)) {
            null
        } else {
            mAbsPath = cleanPath(mAbsPath)
            val file = File(mAbsPath)
            getParent(file)
        }
    }

    fun getParent(file: File?): String? {
        return file?.parent
    }

    fun cleanPath(absPath: String): String {
        var mAbsPath = absPath
        return if (TextUtils.isEmpty(mAbsPath)) {
            mAbsPath
        } else {
            while (mAbsPath.contains("//")) {
                mAbsPath = mAbsPath.replace("//", "/")
            }

            val length = mAbsPath.length
            if (mAbsPath.endsWith("/") && length > 1) {
                mAbsPath = mAbsPath.substring(0, length - 1)
            }
            mAbsPath
        }
    }


    fun exists(absPath: String?): Boolean {
        return if (TextUtils.isEmpty(absPath)) {
            false
        } else {
            val file = File(absPath)
            exists(file)
        }
    }

    fun exists(file: File?): Boolean {
        return file?.exists() ?: false
    }

    fun getFilePathByUri(context: Context, uri: Uri): String? {
        var path: String? = null
        // 以 file:// 开头的
        if (ContentResolver.SCHEME_FILE == uri.scheme) {
            path = uri.path
            return path
        }
        // 以 content:// 开头的，比如 content://media/extenral/images/media/17766
        if (ContentResolver.SCHEME_CONTENT == uri.scheme && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            val cursor = context.contentResolver.query(uri, arrayOf(MediaStore.Images.Media.DATA), null, null, null)
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                    if (columnIndex > -1) {
                        path = cursor.getString(columnIndex)
                    }
                }
                cursor.close()
            }
            return path
        }
        // 4.4及之后的 是以 content:// 开头的，比如 content://com.android.providers.media.documents/document/image%3A235700
        if (ContentResolver.SCHEME_CONTENT == uri.scheme && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (DocumentsContract.isDocumentUri(context, uri)) {
                if (isExternalStorageDocument(uri)) {
                    // ExternalStorageProvider
                    val docId = DocumentsContract.getDocumentId(uri)
                    val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                    val type = split[0]
                    if ("primary".equals(type, ignoreCase = true)) {
                        path = Environment.getExternalStorageDirectory().toString() + "/" + split[1]
                        return path
                    }
                } else if (isDownloadsDocument(uri)) {
                    // DownloadsProvider
                    val id = DocumentsContract.getDocumentId(uri)
                    val contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        java.lang.Long.valueOf(id)
                    )
                    path = getDataColumn(context, contentUri, null, null)
                    return path
                } else if (isMediaDocument(uri)) {
                    // MediaProvider
                    val docId = DocumentsContract.getDocumentId(uri)
                    val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                    val type = split[0]
                    var contentUri: Uri? = null
                    when (type) {
                        "image" -> contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                        "video" -> contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                        "audio" -> contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                    }
                    val selection = "_id=?"
                    val selectionArgs = arrayOf(split[1])
                    path = getDataColumn(context, contentUri, selection, selectionArgs)
                    return path
                }
            }
        }
        return null
    }

    private fun getDataColumn(context: Context, uri: Uri?, selection: String?, selectionArgs: Array<String>?): String? {
        var cursor: Cursor? = null
        val column = "_data"
        val projection = arrayOf(column)
        try {
            cursor = context.contentResolver.query(uri!!, projection, selection, selectionArgs, null)
            if (cursor != null && cursor.moveToFirst()) {
                val columnIndex = cursor.getColumnIndexOrThrow(column)
                return cursor.getString(columnIndex)
            }
        } finally {
            cursor?.close()
        }
        return null
    }

    private fun isExternalStorageDocument(uri: Uri): Boolean {
        return "com.android.externalstorage.documents" == uri.authority
    }

    private fun isDownloadsDocument(uri: Uri): Boolean {
        return "com.android.providers.downloads.documents" == uri.authority
    }

    private fun isMediaDocument(uri: Uri): Boolean {
        return "com.android.providers.media.documents" == uri.authority
    }
}
